﻿using Newtonsoft.Json;
using System;
using System.Diagnostics;

namespace ZhongKeSite.Common.Helper
{
    /// <summary>
    /// 重试类
    /// </summary>
    public class RetryHelper
    {
        /// <summary>
        /// 调用接口重试的公共方法
        /// </summary>
        /// <typeparam name="TResult">返回类型</typeparam>
        /// <param name="title">标题</param>
        /// <param name="service">服务名称</param>
        /// <param name="func">执行方法</param>
        /// <param name="request"></param>
        /// <param name="defaultResult"></param>
        /// <param name="tryTimes">重试次数</param>
        /// <param name="beforeTry">重试之前应该做的事情</param>
        /// <returns></returns>
        public static TResult Execute<TResult>(string title, Func<TResult> func, object request = null, TResult defaultResult = default(TResult), int tryTimes = 1, Action beforeTry = null)
        {
            try
            {
                string requestStr = JsonConvert.SerializeObject(request);
                Stopwatch timer = new Stopwatch();
                timer.Start();
                LogHelper.Info(string.Format(@"标题：{0},请求数据：{1}", title, requestStr));

                var response = func();

                timer.Stop();
                LogHelper.Info(string.Format(@"标题：{0} - 响应；
                耗时：{1}ms；
                请求数据：{2}；
                返回数据：{3}", title, timer.ElapsedMilliseconds, requestStr, JsonConvert.SerializeObject(response)));
                return response;
            }
            catch (Exception ex)
            {
                if (tryTimes > 0)
                {
                    if (beforeTry != null)
                    {
                        beforeTry();
                    }
                    return Execute(title, func, request, defaultResult, tryTimes - 1, beforeTry);
                }
                LogHelper.Error(ex);
                return default(TResult);
            }
        }
    }
}
